package cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@WebServlet(name = "ServletCookie", urlPatterns = "/sc")
public class ServletCookie extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();

            Cookie[] cookies = request.getCookies(); //数组
        if (cookies!=null){
            //
            out.write("上一次访问的时间:");
            for (Cookie c:cookies) {
               if ( c.getName().equals("lastLogin")){
                   // 获取cookie中的值
                   //String value = c.getValue();
                   long aLong = Long.parseLong(c.getValue());// 时间戳
                   Date date = new Date(aLong);
                   out.write(date.toLocaleString());
                   System.out.println(aLong);

               }
            }
        }else {
            out.write("第一次登录时间戳"+System.currentTimeMillis()+"");
        }
        // 存起来
        Cookie cookie = new Cookie("lastLogin",System.currentTimeMillis()+"");
        cookie.setMaxAge(24*60*60); // cookie有效时间  用于浏览器关闭 cookie还存在
        response.addCookie(cookie);
    }
}
